package com.gree.elasticsearch.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gree.elasticsearch.dto.Result;
import com.gree.elasticsearch.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class UrlFilter extends OncePerRequestFilter {
    private Logger logger = LoggerFactory.getLogger(UrlFilter.class.getName());
    private final String INTERCEPTED_URI = "/login";

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String uri = httpServletRequest.getRequestURI();
        logger.debug("user request url is {}", uri);
        if (INTERCEPTED_URI.equals(uri)) {
            PrintWriter printWriter = httpServletResponse.getWriter();
            ObjectMapper objectMapper = new ObjectMapper();
            Result result = ResponseUtil.success(HttpStatus.NOT_FOUND.value(), "", "404 resource not found");
            printWriter.write(objectMapper.writeValueAsString(result));
            printWriter.close();
            return ;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
